from PyQt5.QtWidgets import QWidget,QApplication,QLabel,QVBoxLayout
from PyQt5.QtCore import QTimer,Qt
import sys
import requests
import json
import logging
from utils.common import load_logging_config

with open('system_config.json','r',encoding='utf8') as f:
	sc=json.load(f)
global ip
global port
ip=sc['ip']
port=sc['port']
load_logging_config()

def requests_get(url,response=False):
	try:
		res=requests.get(url)
		if response:
			return res
	except Exception as e:
		print(f'出现异常{e}')
		if response:
			return None

class WidgetA(QWidget):
	def __init__(self,parent=None):
		QWidget.__init__(self)
		self.initUI()

	def initUI(self):
		self.task_progress_label=QLabel(self)
		self.task_progress_messages=[]
		self.task_progress_label.setText('\n'.join(self.task_progress_messages))
		vbox=QVBoxLayout()
		vbox.addWidget(self.task_progress_label)
		self.setLayout(vbox)

		self.show()
		self.timer=QTimer()
		self.timer.timeout.connect(self.manage_bttasks)
		self.timer.start(5000)
		self.task_name=f'调度基准测试任务'
		requests_get(f'http://{ip}:{port}/add_celery_tasks?celery_task_name={self.task_name}')

	def update_task_progress(self, new_message):
		if len(self.task_progress_messages)==5:
			del self.task_progress_messages[0]
		self.task_progress_messages.append(new_message)
		self.task_progress_label.setText('\n'.join(self.task_progress_messages))

	def manage_bttasks(self):
		res=requests_get(f'http://{ip}:{port}/get_cur_bttask',True)
		if res is None:
			self.update_task_progress(f'请求http://{ip}:{port}/get_cur_bttask失败 {time.strftime("%Y-%m-%d %H:%M:%S")}')
			logging.warning(f'请求http://{ip}:{port}/get_cur_bttask失败')
		else:
			cur_bttask=json.loads(res.text)['data']
			self.update_task_progress(f'当前基准测试任务{cur_bttask[0]}{cur_bttask[1]} {time.strftime("%Y-%m-%d %H:%M:%S")}')
			logging.info(f'当前基准测试任务{cur_bttask[0]}{cur_bttask[1]}')
			if cur_bttask[0]==-1 and cur_bttask[1]=='':
				self.update_task_progress(f'当前没有正在运行的任务，正在搜寻可运行的任务 {time.strftime("%Y-%m-%d %H:%M:%S")}')
				logging.info('当前没有正在运行的任务，正在搜寻可运行的任务')
				res=requests_get(f'http://{ip}:{port}/get_bt_tasks')
				if res is None:
					self.update_task_progress(f'请求http://{ip}:{port}/get_bt_tasks失败 {time.strftime("%Y-%m-%d %H:%M:%S")}')
					logging.warning(f'请求http://{ip}:{port}/get_bt_tasks失败')
				else:
					bt_tasks=json.loads(res.text)['data']
					if len(bt_tasks)>0:
						for bt_task in bt_tasks:
							if bt_task[1]==1:
								# requests.get(f'http://{ip}:{port}/set_cur_bttask?id={bt_task[0]}&exec_id={bt_task[4]}&tip={bt_task[3]}&btexec_id={bt_task[5]}')
								# self.update_state(state='PROGRESS',meta={'status':f'开始运行基准测试任务{bt_task[2]}','time':time.strftime("%Y-%m-%d %H:%M:%S")})
								print(bt_task)
								break
			else:
				self.update_task_progress(f'当前正在运行的任务是{cur_bttask[1]} {time.strftime("%Y-%m-%d %H:%M:%S")}')
				logging.info(f'当前正在运行的任务是{cur_bttask[1]}')

	def closeEvent(self,event):
		requests_get(f'http://{ip}:{port}/delete_celery_tasks?celery_task_name={self.task_name}')

if __name__=='__main__':
	app=QApplication(sys.argv)
	w=WidgetA()
	sys.exit(app.exec_())